﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using personalplaner.business.common;
using System.Data.Odbc;
using personalplaner.core.sql;

namespace personalplaner.databasewizard.services
{
    public interface IUpdateDatabaseService : IDatabaseService
    {
    }

    public class UpdateDatabaseService : DatabaseServiceBase, IUpdateDatabaseService
    {
        public UpdateDatabaseService() 
            : base("root/upgrade/file","upd.gc")
		{

		}

		/// <summary>
		/// starting method of thread
		/// </summary>
        public override void Execute(string odbcSource, string user, string password, string database)
        {
            string connectionStr = string.Format("DSN={0};UID={1};PWD={2};Database={3};", odbcSource, user, password, database);
            Settings = new DatabaseSettings
            {
                Connection = new OdbcConnection(connectionStr)
            };

			UpdateFilelist();
			bool tmp = true;
			int index = 0;
			while (tmp)
			{
				tmp = ExecuteSqlFiles(index);
				index++;

                if (!IsNoError)
				{
					tmp = false;
				}
			}

            Mediator.NotifyColleagues<string>("AppendOutputString", string.Format("End of update Database {0}", database));
            //ExecuteFinishEvent();
            Mediator.NotifyColleagues("DatabaseExetueFinished");
		}

		string version;
		private string DBVersion
		{
			get
			{
				if (string.IsNullOrEmpty(version))
				{
					var dv = SimpleQuerry.ExecuteForDataTable(Settings, "select Version from PrsVerwaltung where VerwaltungID = (select MAX(VerwaltungID) from PrsVerwaltung)");
					try
					{
						version = dv.Rows[0][0].ToString();
					}
					catch { }
				}
				return version;
			}
		}

		protected void UpdateFilelist()
		{
			int i=0;
			while (i < SqlFileNames.Count)
			{
				bool fileOK = true;
				try
				{
                    //check if version exists (max version in db)
					if (SqlFileVersions[SqlFileNames[i]].CompareTo(DBVersion) == 0)
						fileOK = false;

					if (fileOK)
					{
						Version dbv = new Version(DBVersion);
						Version fv = new Version(SqlFileVersions[SqlFileNames[i]]);
						
						if (dbv >= fv)
						{
							fileOK = false;
						}
					}
				}
				catch { }

				if (!fileOK)
				{
					SqlFileVersions.Remove(SqlFileNames[i]);
					SqlFileNames.RemoveAt(i);
					i--;
				}
				i++;
			}
		}
    }
}
